const {
  Teacher,
  School,
  Claxx,
  Course,
  HomeWork,
  Score,
  Student,
} = require("../model");
const express = require("express");
const router = express.Router();

//注销
router.post("/delete", async (q, s) => {
  const res = await Teacher.deleteOne(q.body); // 删除第一个匹配的
  s.send({
    success: true,
    data: res,
  });
});

// 注册 - 登录
router.post("/login", async (q, s) => {
  const doc = await Teacher.findOne(q.body); // 返回找到的第一个
  if (doc) {
    s.send({
      msg: "登录成功",
      success: true,
      data: doc,
    });
  } else {
    s.send({
      msg: "登录失败，请先注册！",
      success: false,
      data: {},
    });
  }
});

router.post("/register", async (q, s) => {
  if (!q.body.schoolId) {
    s.send({
      msg: "注册失败，请选择学校",
      success: false,
      data: [],
    });
  } else {
    let res = await Teacher.create(q.body);
    s.send({
      msg: "注册成功",
      success: true,
      data: res,
    });
  }
});

// 填写其他信息
router.post("/edit", async (q, s) => {
  const account = q.body.account;
  console.log(account);
  delete q.body.account;
  // let res = await Teacher.updateOne({ account }, q.body); // 更新第一个匹配的，第二个参数为更新的字段内容
  let res = await Teacher.updateOne({ account }, q.body); // 更新第一个匹配的，第二个参数为更新的字段内容
  s.send({
    msg: "修改成功",
    success: true,
    data: res,
  });
});

// 班级信息修改
router.post("/classEdit", async (q, s) => {
  const { id } = q.body;
  delete q.body.id;
  const doc = await Claxx.findByIdAndUpdate(id, {
    ...q.body,
  });
  s.send({
    msg: "更新成功",
    success: true,
    data: doc,
  });
});

// 获取教师学校里面的所有班级,参数 schoolId
router.post("/getSchoolClassList", async (q, s) => {
  const { id } = q.body;
  const school = await School.findById(id); // 参数是查询参数，精确匹配，结果是匹配的数组
  let classList = await Claxx.find({
    _id: {
      $in: school.classList || [],
    },
  }); // 参数是查询参数，精确匹配，结果是匹配的数组

  const teacherPromiseList = [];
  const studentPromiseList = [];
  const coursePromiseList = [];
  classList.forEach((item) => {
    const teacherPromise = Teacher.find({
      _id: {
        $in: item.teacherIds || [],
      },
    });
    teacherPromiseList.push(teacherPromise);
    //-------------------
    const studentPromise = Student.find({
      _id: {
        $in: item.studentList || [],
      },
    });
    studentPromiseList.push(studentPromise);
    //-----------------------
    const coursePromise = Course.find({
      _id: {
        $in: item.courseList || [],
      },
    });
    coursePromiseList.push(coursePromise);
  });
  const teacherList = await Promise.all([...teacherPromiseList]);
  const studentList = await Promise.all([...studentPromiseList]);
  const courseList = await Promise.all([...coursePromiseList]);
  s.send({
    msg: "获取成功",
    success: true,
    data: {
      teacherList,
      studentList,
      classList,
      courseList,
      school,
    },
  });
});

// 在学校添加一个班级，参数是
//schoolId：教师身上的
// name: 班级名称
// teacherId
// sourceName: 课程名称
router.post("/addClass", async (q, s) => {
  // 增加一个班级
  const courseName = q.body.courseName;
  delete q.body.courseName;
  const claxx = await Claxx.create({
    ...q.body,
    teacherIds: [q.body.teacherId],
    courseList: [],
  });
  // 增加一个课程
  const course = await Course.create({
    name: courseName,
    classId: claxx._id,
    teacherId: q.body.teacherId,
    homeworkList: [null],
  });
  // 把这个课程丢到这个班级里
  claxx.courseList = [...claxx.courseList, course._id];
  claxx.save();
  // 所在的学校关联班级
  const teacherSchoolId = q.body.schoolId;
  const school = await School.findById(teacherSchoolId);
  school.classList = school.classList
    ? [...school.classList, claxx._id]
    : [claxx._id];
  let res = await school.save();
  // 这个班级新建一个课程
  s.send({
    msg: "增加成功",
    success: true,
    data: res,
  });
});

// 教师查询他的所有课程
router.post("/getCourse", async (q, s) => {
  let courseList = await Course.find({ teacherId: q.body.teacherId });

  const classPromiseList = [];
  const teacherPromiseList = [];
  const homeworkPromiseList = [];

  courseList.forEach((item) => {
    const claxxPromise = Claxx.findById(item.classId);
    const teacherPromise = Teacher.findById(item.teacherId);
    const homeworkPromise = HomeWork.find({
      _id: {
        $in: item.homeworkList || [],
      },
    });
    classPromiseList.push(claxxPromise);
    teacherPromiseList.push(teacherPromise);
    homeworkPromiseList.push(homeworkPromise);
  });

  const classList = await Promise.all([...classPromiseList]);
  const teacherList = await Promise.all([...teacherPromiseList]);
  const homeworkList = await Promise.all([...homeworkPromiseList]);

  s.send({
    msg: "查询成功",
    success: true,
    data: {
      courseList,
      classList,
      teacherList,
      homeworkList,
    },
  });
});

// 教师。新增一个课程
/**
 * classId
 *
 */
router.post("/addCourse", async (q, s) => {
  // 增加一个课程
  const course = await Course.create({
    name: q.body.name,
    classId: q.body.classId,
    teacherId: q.body.teacherId,
    homeworkList: [null],
  });
  const claxx = await Claxx.findById(q.body.classId);
  claxx.courseList = claxx.courseList
    ? [...claxx.courseList, course._id]
    : [course._id];
  const res = await claxx.save();
  s.send({
    msg: "增加成功",
    success: true,
    data: res,
  });
});

router.post("/editCourse", async (q, s) => {
  const { id } = q.body;
  delete q.body.id;
  const doc = await Course.findByIdAndUpdate(id, {
    ...q.body,
  });
  s.send({
    msg: "修改成功",
    success: true,
    data: doc,
  });
});

router.post("/getStudentList", async (q, s) => {
  const StudentList = await Student.find({
    classId: q.body.classId,
  });
  // const courseList = await Course.find({
  //   classId: q.body.classId,
  //   teacherId: q.body.teacherId,
  // });
  s.send({
    msg: "查找成功",
    success: true,
    data: StudentList,
  });
});

// 教师加入班级
router.post("/joinClass", async (q, s) => {
  await Teacher.findByIdAndUpdate(q.body.teacherId, {
    classIds: q.body.classId,
  });
  let res = await Claxx.findByIdAndUpdate(q.body.classId, {
    teacherIds: q.body.teacherId,
  });
  s.send({
    msg: "新增成功",
    success: true,
    data: res,
  });
});

// 教师添加作业
/**
 * courseId
 * teacherId
 * ...Homework
 *
 */
router.post("/addHomework", async (q, s) => {
  // 新建一个作业
  const homework = await HomeWork.create(q.body);
  // 作业与课程关联
  let course = await Course.findById(q.body.courseId);
  course.homeworkList = course.homeworkList
    ? [...course.homeworkList, homework._id]
    : [homework._id];
  const res = await course.save();
  s.send({
    msg: "新增成功",
    success: true,
    data: res,
  });
});


/**
 * 获取作业下的学生以及他们的成绩
 * scoreId
 * 
 */
router.post("/getHomeworkWithScore", async (q, s) => {
  // 使用 populate 进行关联查询
  const scoreList = await Score.find({
    _id: {
      $in: q.body.scoreIds,
    }
  }).populate('student').populate('course');

  s.send({
    msg: "新增成功",
    success: true,
    data: scoreList,
  });
});

// 教师批改作业
/**
 * homeworkId
 * scoreId
 * ...Score
 */
router.post("/correctHomework", async (q, s) => {
  let homework = await HomeWork.findById(q.body.homeworkId);
  const scoreId = homework.scoreId;
  const score = await Score.findById(scoreId);
  homework.scoreId = score._id;
  await homework.save();
  score.score = q.body.score;
  score.comment = q.body.comment;
  score.status = q.body.status;
  score.updated = q.body.updated;
  const res = await score.save();
  s.send({
    msg: "批改成功",
    success: true,
    data: res,
  });
});

// 教师解散班级

module.exports = router;
